from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNuberPagination
from meiduo_admin.spu.spus_serializers import SPUViewSetviewSerializer,SPUBrandSimpleSerializers,SPUCategorySerializers
from goods.models import SPU,Brand,GoodsCategory
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
#spu详情
class SPUViewSetview(ModelViewSet):
    pagination_class = MyPageNuberPagination
    serializer_class = SPUViewSetviewSerializer
    queryset =SPU.objects.all()
#新增spu规格
class SPUBrandSimpleView(ListAPIView):
    serializer_class = SPUBrandSimpleSerializers
    queryset = Brand.objects.all()

#spu一级分类
class SPUCategoryView(ListAPIView):
    serializer_class = SPUCategorySerializers
    queryset = GoodsCategory.objects.filter(parent=None).all()


#spu表获取二级和三级分类,通过获取到的category_id来获取他的子级,category_id是一级就获取二级,是二级就获取三级,以此类推
class SPUCategorySubView(ListAPIView):
    serializer_class = SPUCategorySerializers

    def get_queryset(self):
        #获取路由带来的编号分类
        category_id=self.kwargs.get("category_id")
        #获取自分类,这个是自关联的图表,跟省市县表一样,通过父级获取子级
        return GoodsCategory.objects.get(id=category_id).subs.all()

#图片上传
class SPUImageUploadView(APIView):
    def post(self,request):
        # 1,获取参数
        image=request.FILES.get("image")
        buffer=image.read()
        # 2,校验参数
        if not image:
            return Response(status=400)

         # 3,入库(fdfs) FDFS_CONFIG是dev配置的
        client=Fdfs_client(settings.FDFS_CONFIG)
        ret= client.upload_by_buffer(buffer)

        if ret["Status"] !="Upload successed.":
            return Response(status=400)

         # 4,返回响应
        return Response({
            "img_url":settings.BASE_URL+ret.get("Remote file_id")
                         })